<?php

namespace App\Api\Controllers;

use App\Api\Requests\OrderRequest;
use App\Api\TransFormers\OrderTransformer;
use App\Models\Coupon;
use App\Models\Paylog;
use App\Models\WriteOffs;
use App\Models\User;
use App\Models\Order;
use Carbon\Carbon;
use Illuminate\Console\Application;

class OrderController extends BaseController
{

    public function returnData($data = [])
    {
        return ['data' => $data];
    }

    /**
     * 订单二维码
     */
    public function code(OrderRequest $request)
    {
        //获取用户openid
        $openid = $request->get('openid');
        $info = User::where('openid', $openid)->first();
        $userid = $info->id;
        $where = [];
        array_push($where, ['user_id', $userid]);
        //获取优惠券id
        $couponid = $request->get('couponid');
        array_push($where, ['coupon_id', $couponid]);
        $info = Order::where($where)->first();
        if (!$info) {
            return false;
        }
        //获取订单表id
        $id = $info->id;
        $url = $this->orderCode($id);
        $url = ['data' => $url];
        return $url;
    }

    /**
     * 核销
     */
    public function over(OrderRequest $request)
    {
        //订单id
        $orderid = $request->get('id');
        //订单信息
        $info = Order::find($orderid);
        //获取优惠券id
        $couponid = $info->coupon_id;
        $couponinfo = Coupon::where('id',$couponid)->first();
        $data['data']['name'] = $couponinfo->name;
        $data['data']['img'] = $couponinfo->img;
        $data['data']['start'] = $couponinfo->start;
        $data['data']['end'] = $couponinfo->end;
        return $data;
    }

    public function confirm(OrderRequest $request)
    {
//订单id
        $orderid = $request->get('orderid');
        //核销员openid
        $openid = $request->get('openid');
        $userinfo = User::where('openid', $openid)->first();
        //获取核销员的userid
        $userid = $userinfo->id;
        //订单信息
        $info = Order::find($orderid);
        //获取优惠券id
        $couponid = $info->coupon_id;
        $couponinfo = Coupon::where('id', $couponid)->first();
        //获取发布优惠券人的user_id;
        $uid = $couponinfo->user_id;
        $where = [];
        array_push($where, ['user_id', $uid]);
        array_push($where, ['write_offs_id', $userid]);
        $res = WriteOffs::where($where)->first();
//        没有权限
        if(!$res && $uid != $userid){
            $data['data']['type'] = 1;
            $data['data']['content'] = '您不是核销员,没有权限核销';
            return $data;
        }
//        有权限
        if ($info->type == 1) {
            $info->type = 2;
            $info->used_at = Carbon::now();
            if ($info->save()) {
                $data['data']['type'] = 2;
                $data['data']['content'] = '核销成功';
            }
        } else {
            $data['data']['type'] = 3;
            $data['data']['content'] = '此优惠券已失效';
        }
        return $data;
    }
    /**
     * 用户下单
     */
    public function createOrder(OrderRequest $request)
    {
        $userInfo = User::where(['openid' => $request->get('openid')])->first();
        $coupon = Coupon::where(['id' => $request->get('coupon_id')])->first();
        if ($coupon->price == 0) {
            $isLimit = app(Coupon::class)->isLimit($coupon->id, $userInfo->id, $coupon->times);
            if ($isLimit) {
                return [
                    'err_msg' => '已达领取上限'
                ];
            }
        }
        if($coupon->count < 1){
            return [
                'err_msg'=>'已领光'
            ];
        }
        $ins = new Order();
        $ins->user_id = $userInfo['id'];
        $ins->coupon_id = $coupon['id'];
        $ins->money = $coupon['price'];
        $ins->order_no = $this->set_order_no();
        # 如果优惠券金额为0，状态为直接购买成功
        if ($coupon['price'] == 0) {
            $ins->status = 2;
            $ins->paid_at = Carbon::now();
        }

        \DB::beginTransaction();
        try {
            $ins->save();
        } catch (\Exception $error) {
            \DB::rollBack();
            return $this->response->error('订单创建失败', 400);
        }
        $paylog = new Paylog();
        $paylog->order_id = $ins->id;
        $paylog->money = $coupon['price'];
        $paylog->order_no = $ins->order_no;
        # 如果优惠券金额为0，状态为直接购买成功
        if ($coupon['price'] == 0)
            $paylog->status = 1;

        try {
            $paylog->save();
        } catch (\Exception $error) {
            \DB::rollBack();
            return $this->response->error('订单日志创建失败', 400);
        }

        # 如果优惠券金额为0，直接购买成功
        if ($coupon['price'] == 0) {
            # 减少商品 数量
            $coupon = Coupon::findOrFail($request->get('coupon_id'));
            try {
                $coupon->decrement('count');
            } catch (\Exception $error) {
                \DB::rollBack();
                return $this->response->error('订单创建失败', 400);
            }
            \DB::commit();
            return [
                'result' => 'success'
            ];
        }
        \DB::commit();

        $body = [
            'order_no' => $ins->order_no,
            'money' => $ins->money,
            'openid' => $request->get('openid')
        ];
        return $this->setpay($body, $paylog->id);
    }

    # 生成订单号
    public function set_order_no()
    {
        return time();
    }

    /**
     * 订单支付成功，回调地址
     */
    public function orderSucc()
    {
        $options = [
            'app_id' => env('S_WECHAT_APPID'),
        ];
        $app = new \EasyWeChat\Foundation\Application($options + config('wechat'));
        $response = $app->payment->handleNotify(function ($notify, $successful) {
            $order = Order::where('order_no', $notify->out_trade_no)->first();

            if (!$order) {
                return 'Order not exist.';
            }
            if ($order->paid_at) {
                return true;
            }

            $paylog = Paylog::where([
                ['order_no', $notify->out_trade_no]
            ])->first();
            if ($successful) {
                $order->paid_at = Carbon::now();
                $order->status = 2;
                $paylog->status = 1;
            } else {
                $order->status = 5;
                $paylog->status = 2;
            }
            \DB::beginTransaction();
            try {
                $order->save();
            } catch (\Exception $error) {
                \DB::rollBack();
                return $this->response->error('订单状态修改失败', 400);
            }
            try {
                $paylog->save();
            } catch (\Exception $error) {
                \DB::rollBack();
                return $this->response->error('支付日志修改失败', 400);
            }
            \DB::commit();

            if ($order->status == 2) {
                # 减少商品 数量
                $coupon = Coupon::findOrFail($order->coupon_id);
                $coupon->decrement('count');
                return true;
            }
        });
        return $response;
    }


    /**
     * 生成支付参数
     * return 调起支付参数
     */
    public function setpay($body, $paylog_id)
    {
        # >>>>> 生成支付
        $options = [
            'app_id' => env('S_WECHAT_APPID'),
        ];
        //dd($options + config('wechat'));
        $app = new \EasyWeChat\Foundation\Application($options + config('wechat'));
        $payment = $app->payment;
        $attributes = [
            'trade_type' => 'JSAPI', // JSAPI，NATIVE，APP...
            'body' => '附近优惠券',
            'detail' => '优惠券购买',
            'out_trade_no' => $body['order_no'],
            'total_fee' => $body['money'] * 100, // 单位：分
            'notify_url' => url('api/order/orderSucc'), // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'openid' => $body['openid'],
        ];
        $weChatOrder = new \EasyWeChat\Payment\Order($attributes);
        # 统一下单，生成预支付参数prepay_id
        $result = $payment->prepare($weChatOrder);
        # 生成html端调起支付的参数
        $config = $result->toArray();
        if ($result->get('prepay_id')) {
            $paylog = Paylog::where(['id' => $paylog_id])->first();
            $paylog->prepay_id = $result->prepay_id;
            if (!$paylog->save()) {
                return $this->response->error('修改订单日志失败', 400);
            }
            $config = $payment->configForJSSDKPayment($result->prepay_id);
        }
        $config = collect($config);


        return $this->returnData([
            'timeStamp' => $config->get('timestamp'),
            'nonceStr' => $config->get('nonceStr'),
            'package' => $config->get('package'),
            'paySign' => $config->get('paySign'),
            'signType' => $config->get('signType'),
        ]);

    }
}
